package com.didispace.log;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoAppender  extends AppenderSkeleton {
	//连接"localhost:27017"可以直接使用无参构造new MongoClient();
	MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
	
    //private MongoClient mongoClient;
    private MongoDatabase mongoDatabase;
    //List<MongoCredential> credentialsList
    private MongoCollection<BasicDBObject> logsCollection;

//    private String connectionUrl = "mongodb://localhost:27017";
    private String databaseName = "logs";
    private String collectionName = "logs_request";

    @Override
    protected void append(LoggingEvent loggingEvent) {

        if(mongoDatabase == null) {
//            MongoClientURI connectionString = new MongoClientURI(connectionUrl);
//            mongoClient = new MongoClient(connectionString);
            mongoDatabase = mongoClient.getDatabase(databaseName);
            logsCollection = mongoDatabase.getCollection(collectionName, BasicDBObject.class);
        }
        DBObject fields  = new BasicDBObject("test1", loggingEvent.getMessage());
//        logsCollection.insertOne((BasicDBObject) loggingEvent.getMessage());
        logsCollection.insertOne((BasicDBObject)fields);

    }

    @Override
    public void close() {
        if(mongoClient != null) {
            mongoClient.close();
        }
    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    // 省略getter和setter

}